<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑小区' : '新增小区'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
    @update:model-value="handleVisibleChange"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小区名称" prop="name" required>
            <el-input v-model="form.name" placeholder="请输入小区名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="全称" prop="fullName">
            <el-input v-model="form.fullName" placeholder="请输入全称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简介" prop="introduction">
            <el-input v-model="form.introduction" placeholder="请输入简介" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="省市区" prop="selectedArea" required>
            <el-cascader
              v-model="selectedArea"
              :options="areaOptions"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children'
              }"
              placeholder="请选择省市区"
              style="width: 100%"
              @change="handleAreaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入详细地址">
              <template #append>
                <el-button icon="Location" @click="mapDialogVisible = true" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入经度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入纬度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="建筑面积(万方)" prop="buildingArea">
            <el-input v-model="form.buildingArea" placeholder="请输入建筑面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业委会" prop="industryCommittee">
            <el-input v-model="form.industryCommittee" placeholder="请输入业委会" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物业公司" prop="propertyCompany">
            <el-input v-model="form.propertyCompany" placeholder="请输入物业公司" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="绿化率(%)" prop="greeningRate">
            <el-input v-model="form.greeningRate" placeholder="请输入绿化率" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="楼栋数量" prop="buildingNum">
            <el-input v-model="form.buildingNum" placeholder="请输入楼栋数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小区户数" prop="householdNum">
            <el-input v-model="form.householdNum" placeholder="请输入小区户数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单元数" prop="unitNum">
            <el-input v-model="form.unitNum" placeholder="请输入单元数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交付时间" prop="deliverTime">
            <el-date-picker v-model="form.deliverTime" type="date" placeholder="请选择交付时间" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车位收费" prop="parkingFee">
            <el-input v-model="form.parkingFee" placeholder="请输入车位收费" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租赁摊位收费" prop="stallFee">
            <el-input v-model="form.stallFee" placeholder="请输入租赁摊位收费" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行卡所属银行" prop="bankName">
            <el-input v-model="form.bankName" placeholder="请输入所属银行" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资金展示来源" prop="mpSource">
            <el-input v-model="form.mpSource" placeholder="请输入资金展示来源" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="封面图" prop="img">
            <ImageUpload v-model="form.img" limit="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: right; margin-top: 16px;">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-form>
    <AmpMap v-model="mapDialogVisible" @change="handleMapChange" />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import AmpMap from '@/components/AmpMap/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { addCommunity, updateCommunity } from '@/api/house/community'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  areaOptions: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'success'])

const { proxy } = getCurrentInstance()

const formRef = ref(null)
const mapDialogVisible = ref(false)
const selectedArea = ref([])

const form = reactive({
  name: '',
  fullName: '',
  introduction: '',
  address: '',
  longitude: '',
  latitude: '',
  trust: false,
  payway: '',
  phone: '',
  img: '',
  buildingArea: '',
  industryCommittee: '',
  propertyCompany: '',
  propertyServiceRange: [],
  greeningRate: '',
  elevatorNum: '',
  buildingNum: '',
  householdNum: '',
  unitNum: '',
  deliverTime: '',
  propertyFee: '',
  needConfim: false,
  parkingFee: '',
  advertisingFee: '',
  stallFee: '',
  activityPlace: '',
  bankName: '',
  bankCard: '',
  mpSource: '',
  provinceCode: '',
  cityCode: '',
  areaCode: '',
  selectedArea: []
})

const rules = {
  name: [{ required: true, message: '请输入小区名称', trigger: 'blur' }],
  selectedArea: [
    { 
      validator: (rule, value, callback) => {
        if (!selectedArea.value || selectedArea.value.length < 3) {
          callback(new Error('请选择完整的省市区信息'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      resetForm()
      if (props.isEdit && props.formData) {
        Object.assign(form, props.formData)
        // 设置省市区选择器
        if (props.formData.provinceCode && props.formData.cityCode && props.formData.areaCode) {
          selectedArea.value = [props.formData.provinceCode, props.formData.cityCode, props.formData.areaCode]
          form.selectedArea = [props.formData.provinceCode, props.formData.cityCode, props.formData.areaCode]
        } else {
          selectedArea.value = []
          form.selectedArea = []
        }
        
        // 如果有propertyStart/propertyEnd，组装propertyServiceRange
        if (props.formData.propertyStart && props.formData.propertyEnd) {
          form.propertyServiceRange = [new Date(props.formData.propertyStart), new Date(props.formData.propertyEnd)]
        } else {
          form.propertyServiceRange = []
        }
      }
    })
  }
})

function resetForm() {
  Object.assign(form, {
    name: '',
    fullName: '',
    introduction: '',
    address: '',
    longitude: '',
    latitude: '',
    trust: false,
    payway: '',
    phone: '',
    img: '',
    buildingArea: '',
    industryCommittee: '',
    propertyCompany: '',
    propertyServiceRange: [],
    greeningRate: '',
    elevatorNum: '',
    buildingNum: '',
    householdNum: '',
    unitNum: '',
    deliverTime: '',
    propertyFee: '',
    needConfim: false,
    parkingFee: '',
    advertisingFee: '',
    stallFee: '',
    activityPlace: '',
    bankName: '',
    bankCard: '',
    mpSource: '',
    provinceCode: '',
    cityCode: '',
    areaCode: '',
    selectedArea: []
  })
  selectedArea.value = []
  form.selectedArea = []
  formRef.value?.resetFields()
}

function handleAreaChange(value) {
  if (value && value.length >= 3) {
    form.provinceCode = value[0]
    form.cityCode = value[1]
    form.areaCode = value[2]
    form.selectedArea = value
  } else {
    form.provinceCode = ''
    form.cityCode = ''
    form.areaCode = ''
    form.selectedArea = []
  }
}

function handleMapChange(data) {
  if (data.address) {
    form.address = data.address
  }
  form.longitude = data.lng
  form.latitude = data.lat
}

function handleClose() {
  emit('update:visible', false)
  resetForm()
}

function handleVisibleChange(value) {
  emit('update:visible', value)
}

function handleSave() {
  formRef.value.validate(valid => {
    if (valid) {
      // 验证省市区是否已选择
      if (!form.provinceCode || !form.cityCode || !form.areaCode) {
        window.$message?.error?.('请选择完整的省市区信息') || this?.$message?.error('请选择完整的省市区信息')
        return
      }
      
      if (form.propertyServiceRange && form.propertyServiceRange.length === 2) {
        const [start, end] = form.propertyServiceRange
        if (new Date(start) >= new Date(end)) {
          window.$message?.error?.('物业服务开始时间必须小于结束时间') || this?.$message?.error('物业服务开始时间必须小于结束时间')
          return
        }
        form.propertyStart = start
        form.propertyEnd = end
        form.propertyServiceRange = []
      }
      
      const payload = {
        communityId: String(form.communityId ?? ''),
        areaId: String(form.areaId ?? ''),
        roomCode: String(form.roomCode ?? ''),
        floor: String(form.floor ?? ''),
        name: String(form.name ?? ''),
        fullName: String(form.fullName ?? ''),
        introduction: String(form.introduction ?? ''),
        address: String(form.address ?? ''),
        longitude: String(form.longitude ?? ''),
        latitude: String(form.latitude ?? ''),
        phone: String(form.phone ?? ''),
        img: String(form.img ?? ''),
        buildingArea: String(form.buildingArea ?? ''),
        greeningRate: String(form.greeningRate ?? ''),
        buildingNum: String(form.buildingNum ?? ''),
        householdNum: String(form.householdNum ?? ''),
        unitNum: String(form.unitNum ?? ''),
        deliverTime: String(form.deliverTime ?? ''),
        parkingFee: String(form.parkingFee ?? ''),
        stallFee: String(form.stallFee ?? ''),
        bankName: String(form.bankName ?? ''),
        mpSource: String(form.mpSource ?? ''),
        tags: String(form.tags ?? ''),
        area: form.area === '' ? '' : Number(form.area),
        indoorArea: form.indoorArea === '' ? '' : Number(form.indoorArea),
        saleStatus: form.saleStatus === '' ? '' : Number(form.saleStatus),
        collectStatus: form.collectStatus === '' ? '' : Number(form.collectStatus),
        decorationStatus: form.decorationStatus === '' ? '' : Number(form.decorationStatus),
        liveStatus: form.liveStatus === '' ? '' : Number(form.liveStatus),
        useStatus: form.useStatus === '' ? '' : Number(form.useStatus),
        bankStatus: form.bankStatus === '' ? '' : Number(form.bankStatus),
        createDate: String(form.createDate ?? ''),
        saleDate: String(form.saleDate ?? ''),
        contractCollectDate: String(form.contractCollectDate ?? ''),
        collectDate: String(form.collectDate ?? ''),
        decorationDate: String(form.decorationDate ?? ''),
        liveDate: String(form.liveDate ?? ''),
        sort: String(form.sort ?? ''),
        provinceCode: String(form.provinceCode ?? ''),
        cityCode: String(form.cityCode ?? ''),
        areaCode: String(form.areaCode ?? ''),
        isCommunity:false
      }
    
      const request = props.isEdit ? updateCommunity(payload) : addCommunity(payload)
      request.then(() => {
        proxy.$modal.msgSuccess(props.isEdit ? '修改成功' : '新增成功')
        emit('success')
        handleClose()
      }).catch(() => {
        // proxy.$modal.msgError(props.isEdit ? '修改失败' : '新增失败')
      })
    }
  })
}
</script> 